//
//  NewPersonViewController.swift
//  OnceNectar
//
//  Created by 吴凌 on 2018/7/19.
//  Copyright © 2018年 com.inwhoop. All rights reserved.
//

import UIKit
import Networking
import Alamofire
import PKHUD
import SwiftyJSON
import LTScrollView

enum NewPersonSelectType: Int {
    case messageCircle = 0
    case article
    case video
}
class NewPersonViewController: BaseViewController,UITableViewDelegate,UITableViewDataSource,UICollectionViewDelegate,UICollectionViewDataSource,UIScrollViewDelegate {
    
    @IBOutlet weak var scrollView: UIScrollView!
    @IBOutlet weak var bgImg: UIImageView!
    @IBOutlet weak var otherView: UIView!
    @IBOutlet weak var mineView: UIView!
    @IBOutlet weak var tableView1: UITableView!
    @IBOutlet weak var tableView2: UITableView!
    @IBOutlet weak var collectionView: UICollectionView!
    
    @IBOutlet weak var otherUserImg: BaseCircleImageView!
    
    @IBOutlet weak var otherUserName: UILabel!
    @IBOutlet weak var followButton: UIButton!
    @IBOutlet weak var otherLv: UIButton!
    @IBOutlet weak var otherMatch: UILabel!
    @IBOutlet weak var otherAttBtn: UIButton!
    @IBOutlet weak var otherFanBtn: UIButton!
    
    @IBOutlet weak var userImg: BaseCircleImageView!
    @IBOutlet weak var userName: UILabel!
    @IBOutlet weak var userLv: UIButton!
    @IBOutlet weak var userAttBtn: UIButton!
    @IBOutlet weak var userFanBtn: UIButton!
    @IBOutlet weak var userGenderBtn: UIButton!
    @IBOutlet weak var oldLabel: UILabel!
    
    @IBOutlet weak var cornerSelectionView: CornerSelectionView!
    
    var isMine:Bool = false
    var userId:String?
    var model: commentUserModel?
    var articleData:[ArticleModel] = []
    var videoData:[VideoModel] = []
    var circleData: [CircleModel] = []
    
    private var selectType: NewPersonSelectType = .messageCircle
    
    var modelMe:circleMemberListModel?
    // 顶部刷新
    let header = MJRefreshNormalHeader()
    // 底部刷新
    let footer = MJRefreshAutoNormalFooter()

    var page1:Int = 1
    var page2:Int = 1
    var page3:Int = 1
    var totalPage1:Int = 0
    var totalPage2:Int = 0
    var totalPage3:Int = 0
    let pageMaxCount = 16
    var pageCount = 0
    let messageCircleLRMargin: CGFloat = 27
    let messageCircleCellSize: CGFloat = {
        return (ScreenWidth - 40 - 10 * 3  - 27 * 2) / 4
    }()
    let messageCircleTBMargin: CGFloat = 18
    let messageCircleMargin: CGFloat = 24
    
    override func viewDidLoad() {
        super.viewDidLoad()
        setUI()
//        fetchMyUserData()
    }
    
    override func viewWillAppear(_ animated: Bool) {
        super.viewWillAppear(animated)
        headerRefresh()
    }
    
    override func setNavigation() {
        
    }

    func setUI() {
        cornerSelectionView.show(titles: ["圈子", "文章", "视频"]) {[unowned self] (index) in
            var corner: UIRectCorner!
            switch index {
            case 0:
                corner = .topRight
                self.collectionView.isHidden = false
                self.tableView1.isHidden = true
                self.tableView2.isHidden = true
                if self.circleData.count == 0 {
                    self.headerRefresh()
                }
            case 2:
                corner = .topLeft
                self.collectionView.isHidden = true
                self.tableView1.isHidden = true
                self.tableView2.isHidden = false
                if self.videoData.count == 0 {
                    self.headerRefresh()
                }
            default:
                corner = [.topRight, .topLeft]
                self.collectionView.isHidden = true
                self.tableView1.isHidden = false
                self.tableView2.isHidden = true
                if self.articleData.count == 0 {
                    self.headerRefresh()
                }
            }
            self.scrollView.mj_footer=self.footer
            self.selectType = NewPersonSelectType(rawValue: index)!
        }
        
        collectionView.delegate = self
        collectionView.dataSource = self
        collectionView.collectionViewLayout = getFlowLayout()
        collectionView.register(UINib.init(nibName: "\(MessageCirclePersonalCenterCollectionViewCell.self)", bundle: nil), forCellWithReuseIdentifier: "\(MessageCirclePersonalCenterCollectionViewCell.self)")
        
        tableView1.dataSource = self
        tableView1.delegate = self
        tableView1.register(UINib(nibName: "\(ConsultaionTableViewCell.self)", bundle: nil), forCellReuseIdentifier: "\(ConsultaionTableViewCell.self)")
        
        tableView2.dataSource = self
        tableView2.delegate = self
        tableView2.register(UINib(nibName: "\(ConsultaionTableViewCell.self)", bundle: nil), forCellReuseIdentifier: "\(ConsultaionTableViewCell.self)")
        
        let headerAction:Selector = #selector(headerRefresh)
        header.setRefreshingTarget(self, refreshingAction: headerAction)
        scrollView.mj_header = header
        let footerAction:Selector = #selector(footerRefresh)
        footer.setRefreshingTarget(self, refreshingAction: footerAction)
        scrollView.mj_footer = footer
        
        followButton.layer.cornerRadius = followButton.height / 2
        followButton.layer.borderColor = UIColor.white.cgColor
        followButton.layer.borderWidth = 1.0
    }
    
    func setData() {
        if isMine {
            self.title = "个人主页"
        }else {
            self.title = model?.nickname
        }
        
        bgImg.sd_setImage(with: appendUrl(suffix: (model?.headIcon)!), completed: nil)
        if isMine {
            mineView.isHidden = false
            userName.text = model?.nickname
            userImg.sd_setImage(with: appendUrl(suffix: (model?.headIcon)!), completed: nil)
            userLv.setTitle(model?.grade?.gradeCode, for: UIControlState.normal)
            userGenderBtn.isSelected = model?.sexy == "男" ? false : true
            let age :String = (model?.age)!
            oldLabel.text = "\(age)岁"
            let cocernCount:String = (model?.concernsAmount)!
            userAttBtn.setTitle("关注 \(cocernCount)", for: UIControlState.normal)
            let fanCount:String = (model?.fansAmount)!
            userFanBtn.setTitle("粉丝 \(fanCount)", for: UIControlState.normal)
        }else {
            otherView.isHidden = false
            otherUserName.text = model?.nickname
            otherUserImg.sd_setImage(with: appendUrl(suffix: (model?.headIcon)!), completed: nil)
            otherLv.setTitle(model?.grade?.gradeCode, for: UIControlState.normal)
            otherMatch.text = model?.matchDegree
            let cocernCount:String = (model?.concernsAmount)!
            otherAttBtn.setTitle("关注 \(cocernCount)", for: UIControlState.normal)
            let fanCount:String = (model?.fansAmount)!
            otherFanBtn.setTitle("粉丝 \(fanCount)", for: UIControlState.normal)
            followButton.isSelected = model?.concernType == "1" ? true : false
        }
        headerRefresh()
    }
    
    // 顶部刷新
    @objc func headerRefresh(){
        if self.selectType == .messageCircle {
            page1 = 0
        }else if self.selectType == .article {
            page2 = 0
        }else if self.selectType == .video {
            page3 = 0
        }
        fetchMyUserData()
        self.footerRefresh()
        
    }
    // 底部刷新
    @objc func footerRefresh(){
        if self.selectType == .messageCircle {
            page1 += 1
            var parameters: [String: Any] = ["page":page1,"pageSize":10,"type":1]
            if !self.isMine {
                parameters["userId"] = self.userId
            }
            self.fetchCircleList(parameters: parameters)
        }else if self.selectType == .article {
            page2 += 1
            var parameters: [String: Any] = ["page":page2,"pageSize":10,"type":1]
            if !self.isMine {
                parameters["otherUserId"] = self.userId
            }
            self.fetchArticleList(parameters: parameters)
        }else if self.selectType == .video {
            page3 += 1
            var parameters: [String: Any] = ["page":page3,"pageSize":10,"type":1]
            if !self.isMine {
                parameters["otherUserId"] = self.userId
            }
            self.fetchVideoList(parameters: parameters)
        }
        
    }
    
    func getFlowLayout() -> UICollectionViewFlowLayout {
        var flowLayout = UICollectionViewFlowLayout()
        switch selectType {
        case .messageCircle:
            //一排显示四个,两排就是八个
            pageCount = 16
            while (pageCount % pageMaxCount != 0) {
                pageCount += 1;
            }
            
            flowLayout = UICollectionViewFlowLayout()
            flowLayout.itemSize = CGSize(width: messageCircleCellSize, height: messageCircleCellSize * 1.5)
            flowLayout.scrollDirection = .vertical
            flowLayout.minimumInteritemSpacing = 10;
            flowLayout.minimumLineSpacing = 10;
            flowLayout.sectionInset = UIEdgeInsets(top: 0, left: 10, bottom: 0, right: 10)
        case .article:break
            
        case .video:break
        }
        
        return flowLayout
    }
    
    override func didReceiveMemoryWarning() {
        super.didReceiveMemoryWarning()
    }
    
    @IBAction func editUserInfoAction(_ sender: UIButton) {
        let editingInformationVC = EditingInformationViewController(nibName: "\(EditingInformationViewController.self)", bundle: nil)
        editingInformationVC.userInfo = MineInfoModel.share.userInfModel!
        navigationController?.pushViewController(editingInformationVC, animated: true)
    }
    
    @IBAction func followBtnAction(_ sender: UIButton) {
        if sender.isSelected {
            attentionCancelUser(parameters: ["concernUserId": userId!])
        }else {
            attentionUser(parameters: ["concernUserId": userId!])
        }
    }
    
    func tableView(_ tableView: UITableView, numberOfRowsInSection section: Int) -> Int {
        if tableView.isEqual(self.tableView1) {
            return self.articleData.count
        }else {
            return self.videoData.count
        }
    }

    func tableView(_ tableView: UITableView, cellForRowAt indexPath: IndexPath) -> UITableViewCell {
        let cell = tableView.dequeueReusableCell(withIdentifier: "\(MessageCirclePersonalCenterTableViewCell.self)") as? MessageCirclePersonalCenterTableViewCell
        if tableView.isEqual(self.tableView1) {
            let cell = tableView.dequeueReusableCell(withIdentifier: "\(ConsultaionTableViewCell.self)") as? ConsultaionTableViewCell
            cell?.showConsultaionData(model: articleData[indexPath.row])
            return cell!
        }else {
            let cell = tableView.dequeueReusableCell(withIdentifier: "\(ConsultaionTableViewCell.self)") as? ConsultaionTableViewCell
            cell?.showVideoData(model: videoData[indexPath.row])
            return cell!
        }
    }
    
    func tableView(_ tableView: UITableView, heightForRowAt indexPath: IndexPath) -> CGFloat {
        return 260
    }
    
    func tableView(_ tableView: UITableView, didSelectRowAt indexPath: IndexPath) {
        if tableView == self.tableView2 {
            let vc = VideoDetailViewController(nibName: ("\(VideoDetailViewController.self)"), bundle: nil, type: HomeVCSelect.video)
            vc.model = videoData[indexPath.row]
            self.navigationController?.pushViewController(vc, animated: true)
        }
        else {
            let vc = ConsultationDetailViewController(nibName: ("\(ConsultationDetailViewController.self)"), bundle: nil, type: HomeVCSelect.news)
            vc.model = articleData[indexPath.row]
            self.navigationController?.pushViewController(vc, animated: true)
        }
    }

    // MARK: - CollectionViewDatasource
    func collectionView(_ collectionView: UICollectionView, numberOfItemsInSection section: Int) -> Int {
        return self.circleData.count
    }

    func collectionView(_ collectionView: UICollectionView, cellForItemAt indexPath: IndexPath) -> UICollectionViewCell {
        let cell = collectionView.dequeueReusableCell(withReuseIdentifier: "\(MessageCirclePersonalCenterCollectionViewCell.self)", for: indexPath) as! MessageCirclePersonalCenterCollectionViewCell
        cell.contentView.isHidden = indexPath.item > pageCount - (pageCount - 16)

        let model = self.circleData[indexPath.row]
        cell.showImageView.sd_setImage(with: appendUrl(suffix: model.coverPath!), completed: nil)
        cell.countLabel.text = model.circleName
        return cell
    }

    func collectionView(_ collectionView: UICollectionView, didSelectItemAt indexPath: IndexPath) {
        let messageCircleDetailVC = MessageCircleDetailViewController(nibName: "\(MessageCircleDetailViewController.self)", bundle: nil)
        let model: CircleModel? = self.circleData[indexPath.row]
        messageCircleDetailVC.titleLabel(text: (model?.circleName)!, nil)
        messageCircleDetailVC.showRightButtonType = .share
        messageCircleDetailVC.circieId = model?.id
        self.navigationController?.pushViewController(messageCircleDetailVC, animated: true)
    }
    
    /// 获取圈子列表
    func fetchMyUserData() -> Void {
        var params:[String:String]?
        if userId != nil {
            if MineInfoModel.share.userInfModel?.id != userId {
                params = ["otherUserId":userId!]
            }else {
                isMine = true
            }
        }else{
            isMine = true
        }
        let requesturl = "\(BaseURL)\(userDetailUrl)"
        Alamofire.request(requesturl, method: .get,
                          parameters: params ,
                          encoding: URLEncoding.default,
                          headers: ["token":MineInfoModel.share.token!]).responseJSON {
                            (response) in
                            if(response.error == nil){
                                if let result = response.result.value as? NSDictionary
                                {
                                    let json = JSON(result)
                                    if json["code"].int == 1{
                                        let dic = json["data"].dictionary!
                                        var amodel = commentUserModel(fromDic: dic)
                                        amodel.initGrade(dic: (dic["grade"]?.dictionary)!)
                                        self.model = amodel
                                        self.setData()
                                    }else if json["code"].int == 100{
                                        self.showToast(msg:json["message"].string!)
                                        let loginVC = LoginViewController(nibName: "\(LoginViewController.self)", bundle: nil)
                                    self.navigationController?.pushViewController(loginVC, animated: true)
                                    }
                                    else{
                                        self.showToast(msg:json["message"].string!)
                                    }
                                }
                            }else{
                                print("请求失败\(String(describing: response.error))")
                            }
        }
    }
    
    /// 关注用户
    func attentionUser(parameters: [String:String]) -> Void {
        HUD.show(.label("加载中..."))
        let requesturl = "\(BaseURL)\(attentionUserUrl)"
        
        Alamofire.request(requesturl, method: .post,
                          parameters: parameters,
                          encoding: URLEncoding.default,
                          headers: ["token":MineInfoModel.share.token!]).responseJSON {
                            (response) in
                            HUD.hide()
                            
                            if(response.error == nil){
                                
                                if let result = response.result.value as? NSDictionary
                                {
                                    let json = JSON(result)
                                    if json["code"].int == 1{
                                        self.showToast(msg:"关注成功")
                                        self.followButton.isSelected = true
                                    }else if json["code"].int == 100{
                                        self.showToast(msg:json["message"].string!)
                                        let loginVC = LoginViewController(nibName: "\(LoginViewController.self)", bundle: nil)
                                        self.navigationController?.pushViewController(loginVC, animated: true)
                                    }
                                        
                                    else{
                                        self.showToast(msg:json["message"].string!)
                                    }
                                }
                            }else{
                                self.showToast(msg:"关注失败")
                                print("请求失败\(String(describing: response.error))")
                            }
                            
        }
        
    }
    
    /// 取消关注用户
    func attentionCancelUser(parameters: [String:String]) -> Void {
        HUD.show(.label("加载中..."))
        let requesturl = "\(BaseURL)\(attentionCancelUserUrl)"
        Alamofire.request(requesturl, method: .post,
                          parameters: parameters,
                          encoding: URLEncoding.default,
                          headers: ["token":MineInfoModel.share.token!]).responseJSON {
                            (response) in
                            HUD.hide()
                            
                            if(response.error == nil){
                                
                                if let result = response.result.value as? NSDictionary
                                {
                                    let json = JSON(result)
                                    if json["code"].int == 1{
                                        self.showToast(msg:"取消关注成功")
                                        self.followButton.isSelected = false
                                    }else if json["code"].int == 100{
                                        self.showToast(msg:json["message"].string!)
                                        let loginVC = LoginViewController(nibName: "\(LoginViewController.self)", bundle: nil)
                                        self.navigationController?.pushViewController(loginVC, animated: true)
                                    }
                                        
                                    else{
                                        self.showToast(msg:json["message"].string!)
                                    }
                                }
                            }else{
                                self.showToast(msg:"请求失败")
                                print("请求失败\(String(describing: response.error))")
                            }
                            
        }
        
    }
    
    /// 获取文章列表
    func fetchArticleList(parameters:[String:Any]) -> Void {
        let requesturl = "\(BaseURL)\(myContentUrl)"
        Alamofire.request(requesturl, method: .get,
                          parameters: parameters ,
                          encoding: URLEncoding.default,
                          headers: ["token":MineInfoModel.share.token!]).responseJSON {
                            (response) in
                            if(response.error == nil){
                                
                                if let result = response.result.value as? NSDictionary
                                {
                                    let json = JSON(result)
                                    if json["code"].int == 1{
                                        self.totalPage2 = json["data"]["total"].int!
                                        let arr = json["data"]["rows"].array!
                                        
                                        if self.page2 == 1{
                                            self.articleData.removeAll()
                                            self.scrollView.mj_header.endRefreshing()
                                        }
                                        else{
                                            self.scrollView.mj_footer.endRefreshing()
                                        }
                                        for subject in arr{
                                            let dic = subject.dictionary!
                                            var model = ArticleModel(fromDic: dic)
                                            
                                            let labels = dic["labels"]?.array!
                                            
                                            model.initLabels(arr: labels!)
                                            
                                            let label = dic["label"]
                                            if !(label?.isEmpty)!{
                                                model.initLabel(dic: (label?.dictionary!)!)
                                            }
                                            let author = dic["author"]
                                            if !(author?.isEmpty)!{
                                                model.initAuthor(dic: (author?.dictionary!)!)
                                            }
                                            let grade = dic["author"]!["grade"]
                                            if !grade.isEmpty{
                                                model.author?.initGrade(dic: (grade.dictionary!))
                                            }
                                            let channel = dic["channel"]
                                            if !(channel?.isEmpty)!{
                                                model.initChannel(dic: (channel?.dictionary!)!)
                                            }
                                            
                                            self.articleData.append(model)
                                        }
                                        if self.totalPage2 == self.articleData.count{
                                            self.scrollView.mj_footer = nil
                                        }
                                        else{
                                            self.scrollView.mj_footer = self.footer
                                        }
                                        self.tableView1.reloadData()
                                    }else if json["code"].int == 100{
                                        self.showToast(msg:json["message"].string!)
                                        let loginVC = LoginViewController(nibName: "\(LoginViewController.self)", bundle: nil)
                                        self.navigationController?.pushViewController(loginVC, animated: true)
                                    }
                                    else{
                                        if self.page2 == 1{
                                            self.scrollView.mj_header.endRefreshing()
                                        }
                                        else{
                                            self.scrollView.mj_footer.endRefreshing()
                                        }
                                        
                                        self.showToast(msg:json["message"].string!)
                                    }
                                }
                            }else{
                                if self.page2 == 1{
                                    self.scrollView.mj_header.endRefreshing()
                                }
                                else{
                                    self.scrollView.mj_footer.endRefreshing()
                                }
                                print("请求失败\(String(describing: response.error))")
                            }
                            
        }
        
    }
    
    /// 获取视频列表
    func fetchVideoList(parameters:[String:Any]) -> Void {
        let requesturl = "\(BaseURL)\(myContentUrl)"
        Alamofire.request(requesturl, method: .get,
                          parameters: parameters ,
                          encoding: URLEncoding.default,
                          headers: ["token":MineInfoModel.share.token!]).responseJSON {
                            (response) in
                            if(response.error == nil){
                                
                                if let result = response.result.value as? NSDictionary
                                {
                                    let json = JSON(result)
                                    if json["code"].int == 1{
                                        self.totalPage3 = json["data"]["total"].int!
                                        let arr = json["data"]["rows"].array!
                                        
                                        if self.page3 == 1{
                                            self.videoData.removeAll()
                                            self.scrollView.mj_header.endRefreshing()
                                        }
                                        else{
                                            self.scrollView.mj_footer.endRefreshing()
                                        }
                                        for subject in arr{
                                            
                                            let dic = subject.dictionary!
                                            var model = VideoModel(fromDic: dic)
                                            let labels = dic["labels"]?.array!
                                            
                                            model.initLabels(arr: labels!)
                                            
                                            let label = dic["label"]
                                            if !(label?.isEmpty)!{
                                                model.initLabel(dic: (label?.dictionary!)!)
                                            }
                                            let author = dic["author"]
                                            if !(author?.isEmpty)!{
                                                model.initAuthor(dic: (author?.dictionary!)!)
                                            }
                                            let grade = dic["author"]!["grade"]
                                            if !grade.isEmpty{
                                                model.author?.initGrade(dic: (grade.dictionary!))
                                            }
                                            let channel = dic["channel"]
                                            if !(channel?.isEmpty)!{
                                                model.initChannel(dic: (channel?.dictionary!)!)
                                            }
                                            
                                            self.videoData.append(model)
                                        }
                                        if self.totalPage3 == self.videoData.count{
                                            self.tableView2.mj_footer=nil
                                        }
                                        else{
                                            self.scrollView.mj_footer = self.footer
                                        }
                                        self.tableView2.reloadData()
                                    }else if json["code"].int == 100{
                                        self.showToast(msg:json["message"].string!)
                                        let loginVC = LoginViewController(nibName: "\(LoginViewController.self)", bundle: nil)
                                        self.navigationController?.pushViewController(loginVC, animated: true)
                                    }
                                    else{
                                        if self.page3 == 1{
                                            self.scrollView.mj_header.endRefreshing()
                                        }
                                        else{
                                            self.scrollView.mj_footer.endRefreshing()
                                        }
                                        self.showToast(msg:json["message"].string!)
                                    }
                                }
                            }else{
                                if self.page3 == 1{
                                    self.scrollView.mj_header.endRefreshing()
                                }
                                else{
                                    self.scrollView.mj_footer.endRefreshing()
                                }
                                print("请求失败\(String(describing: response.error))")
                            }
                            
        }
        
    }
    
    /// 获取圈子列表
    func fetchCircleList(parameters:[String:Any]) -> Void {
        let requesturl = "\(BaseURL)\(userCircleUrl)"
        Alamofire.request(requesturl, method: .get,
                          parameters: parameters ,
                          encoding: URLEncoding.default,
                          headers: ["token":MineInfoModel.share.token!]).responseJSON {
                            (response) in
                            if(response.error == nil){
                                
                                if let result = response.result.value as? NSDictionary
                                {
                                    let json = JSON(result)
                                    if json["code"].int == 1{
                                        self.totalPage1 = json["data"]["total"].int!
                                        let arr = json["data"]["rows"].array!
                                        
                                        if self.page1 == 1{
                                            self.circleData.removeAll()
                                            self.scrollView.mj_header.endRefreshing()
                                        }
                                        else{
                                            self.scrollView.mj_footer.endRefreshing()
                                        }
                                        for subject in arr{
                                            
                                            let dic = subject.dictionary!
                                            let model = CircleModel(fromDic: dic)
                                            
                                            self.circleData.append(model)
                                        }
                                        if self.totalPage1 == self.circleData.count{
                                            self.scrollView.mj_footer=nil
                                        }
                                        else{
                                            self.scrollView.mj_footer = self.footer
                                        }
                                        self.collectionView.reloadData()
                                        
                                    }else if json["code"].int == 100{
                                        self.showToast(msg:json["message"].string!)
                                        let loginVC = LoginViewController(nibName: "\(LoginViewController.self)", bundle: nil)
                                        self.navigationController?.pushViewController(loginVC, animated: true)
                                    }
                                    else{
                                        if self.page1 == 1{
                                            self.scrollView.mj_header.endRefreshing()
                                        }
                                        else{
                                            self.scrollView.mj_footer.endRefreshing()
                                        }
                                        self.showToast(msg:json["message"].string!)
                                    }
                                }
                            }else{
                                if self.page1 == 1{
                                    self.scrollView.mj_header.endRefreshing()
                                }
                                else{
                                    self.scrollView.mj_footer.endRefreshing()
                                }
                                print("请求失败\(String(describing: response.error))")
                            }
        }
    }
    func scrollViewDidScroll(_ scrollView: UIScrollView) {
        if scrollView == self.scrollView {
            var placeholderOffset : CGFloat  = 0
            let kItemheight :CGFloat = 40
            if self.selectType ==  .messageCircle{
                
                if self.collectionView.contentOffset.y > self.bgImg.mj_size.height - kItemheight {
                    placeholderOffset = self.bgImg.mj_size.height - kItemheight
                }
                else {
                    placeholderOffset = self.collectionView.contentOffset.y
                }
                self.tableView1.setContentOffset(CGPoint.init(x: 0, y: placeholderOffset), animated: false)
                self.tableView2.setContentOffset(CGPoint.init(x: 0, y: placeholderOffset), animated: false)
            }
            else if self.selectType ==  .article {
                if self.tableView1.contentOffset.y > self.bgImg.mj_size.height - kItemheight {
                    placeholderOffset = self.bgImg.mj_size.height - kItemheight;
                } else {
                    placeholderOffset = self.tableView1.contentOffset.y;
                }
                
                self.collectionView.setContentOffset(CGPoint.init(x: 0, y: placeholderOffset), animated: false)
                self.tableView2.setContentOffset(CGPoint.init(x: 0, y: placeholderOffset), animated: false)
            }else {
                if self.tableView2.contentOffset.y > self.bgImg.mj_size.height - kItemheight {
                    placeholderOffset = self.bgImg.mj_size.height - kItemheight;
                } else {
                    placeholderOffset = self.tableView2.contentOffset.y;
                }
                
                self.collectionView.setContentOffset(CGPoint.init(x: 0, y: placeholderOffset), animated: false)
                self.tableView1.setContentOffset(CGPoint.init(x: 0, y: placeholderOffset), animated: false)
            }
        }else {
            let placeHolderHeight : CGFloat = self.bgImg.mj_size.height - 40
            
            let offsetY : CGFloat = scrollView.contentOffset.y
            
            if (offsetY >= 0 && offsetY <= placeHolderHeight) {
                self.scrollView.isScrollEnabled = true
                self.scrollView.y = -offsetY;
            }
            else if offsetY > placeHolderHeight {
                self.scrollView.y = -placeHolderHeight
                self.scrollView.isScrollEnabled = false
            }
            else if offsetY < 0 {
                self.scrollView.y =  -offsetY
                self.scrollView.isScrollEnabled = false
            }
        }
    }

    @IBAction func pushAtt(_ sender: Any) {
        let vc = FansViewController()
        vc.title = "关注"
        self.navigationController?.pushViewController(vc, animated: true)
    }
    @IBAction func pushFan(_ sender: Any) {
        let vc = FansViewController()
        vc.title = "粉丝"
        self.navigationController?.pushViewController(vc, animated: true)
    }
}
